﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Web.UI.WebControls;
using GioHangViet.Models;

namespace GioHangViet.Areas.Admin.Models
{
    public class ProcessAlias
    {
        private GoLungTungModel db = new GoLungTungModel();

        /// <summary>
        /// Description:    Return a alias string
        /// </summary>
        /// <param name="processAlias"> </param>
        /// <param name="needConvert">Chuỗi cần sinh Alias</param>
        /// <param name="tableName">Tên bảng</param>
        /// <param name="columnName">Tên cột</param>
        /// <returns>chuỗi alias</returns>
        public string CreateAlias(string needConvert, String tableName, String columnName)
        {
            string stringConverted = ConvertToUnSign(needConvert).Trim(); //Remove sign in string.
            //
            // Remove special character.
            //
            stringConverted = RemoveSpecialCharacters(stringConverted);
            string alias = null;
            int count;
            switch (tableName)
            {
                case "Authors":
                    count = (from author in db.Authors where (author.Alias.Contains(stringConverted) ) select author).Count();
                    if (count > 0)
                    {
                        alias = stringConverted + (count + 1).ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        alias = stringConverted;
                    }
                    //alias = (from a in db.Authors select a.Alias);
                    break;
                case "Categories":
                    count = (from categories in db.Categories where (categories.Alias.Contains(stringConverted)) select categories).Count();
                    if (count > 0)
                    {
                        alias = stringConverted + (count + 1).ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        alias = stringConverted;
                    }
                    break;
                case "Comters":
                    count = (from comters in db.Comters where (comters.Alias.Contains(stringConverted)) select comters).Count();
                    if (count > 0)
                    {
                        alias = stringConverted + (count + 1).ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        alias = stringConverted;
                    }
                    break;
                case "Languages":
                    count =
                        (from languages in db.Languages where (languages.Alias.Contains(stringConverted)) select languages).Count();
                    if (count > 0)
                    {
                        alias = stringConverted + (count + 1).ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        alias = stringConverted;
                    }
                    break;
                case "Newses":
                    count = (from news in db.Newses where (news.Alias.Contains(stringConverted)) select news).Count();
                    if (count > 0)
                    {
                        alias = stringConverted + (count + 1).ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        alias = stringConverted;
                    }
                    break;
                case "Products":
                    count = (from product in db.Products where (product.Alias.Contains(stringConverted)) select product).Count();
                    if (count > 0)
                    {
                        alias = stringConverted + (count + 1).ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        alias = stringConverted;
                    }
                    break;
                case "Promotions":
                    count=(from promotion in db.Promotions where (promotion.Alias.Contains(stringConverted)) select  promotion).Count();
                    if (count > 0)
                    {
                        alias = stringConverted + (count + 1).ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        alias = stringConverted;
                    }
                    break;
                case "Publishers":
                    count = (from publish in db.Publishers where (publish.Alias.Contains(stringConverted)) select publish).Count();
                    if (count > 0)
                    {
                        alias = stringConverted + (count + 1).ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        alias = stringConverted;
                    }
                    break;

            }
            return alias;
        }

        /// <summary>
        /// Create by: HiepVV
        /// Description: Remove sign in string.
        /// </summary>
        /// <param name="s">string need edit</param>
        /// <returns></returns>
        public static string ConvertToUnSign(string s)
        {
            var regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            var temp = s.Normalize(NormalizationForm.FormD);
            return regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D').Replace(' ', '-');
        }

        /// <summary>
        /// Hàm remove các định dạng HTML
        /// </summary>
        /// <param name="htmlString"></param>
        /// <returns></returns>
        public static string RemoveHtmlTagsUsingRegex(string htmlString)
        {
            var result = Regex.Replace(htmlString, "<.*?>", string.Empty);
            return result;
        }
        /// <summary>
        /// Hàm remove các ký tự đặc biệt.
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RemoveSpecialCharacters(string str)
        {
            return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
        }

        private static readonly Cache Cache = HttpContext.Current.Cache;

        public static string ConvertDMYtoMDY(string pDDMMYY)
        {
            var tempDate = pDDMMYY.Trim();
            var mstrShortDate = tempDate.Substring(0, tempDate.LastIndexOf("/", StringComparison.Ordinal) + 5);
            return mstrShortDate.Substring(mstrShortDate.IndexOf("/", StringComparison.Ordinal) + 1, mstrShortDate.LastIndexOf("/", StringComparison.Ordinal) - mstrShortDate.IndexOf("/", StringComparison.Ordinal) - 1) + "/" + mstrShortDate.Substring(0, mstrShortDate.IndexOf("/", StringComparison.Ordinal)) + "/" + mstrShortDate.Substring(mstrShortDate.LastIndexOf("/", StringComparison.Ordinal) + 1, mstrShortDate.Length - mstrShortDate.LastIndexOf("/", StringComparison.Ordinal) - 1);
        }

        public static string ConvertDMYtoMMMddyyyy(string pDDMMYY)
        {
            var mDateId = Convert.ToDateTime(ConvertDMYtoMDY(pDDMMYY));

            return mDateId.ToString("MMM dd yyyy");
        }

        public static string ConvertMDYtoDMY(object pMMDDYY)
        {
            if (pMMDDYY.ToString().Trim() != "")
            {
                return Convert.ToDateTime(pMMDDYY.ToString().Trim()).ToString("dd/MM/yy");
            }
            return "";
        }

        public static string ConvertMDYtoDDMMYYYY(object pMMDDYY)
        {
            if (pMMDDYY.ToString().Trim() != "")
            {
                return Convert.ToDateTime(pMMDDYY.ToString().Trim()).ToString("dd/MM/yyyy");
            }
            return "";
        }

        public static string ConvertDMYtoMDY(object pDDMMYY)
        {
            if (pDDMMYY.ToString().Trim() != "")
            {
                return Convert.ToDateTime(pDDMMYY.ToString().Trim()).ToString("MM/dd/yy");
            }
            return "";
        }

        public static string ConvertDMYtoMMDDYYYY(object pDDMMYY)
        {
            if (pDDMMYY.ToString().Trim() != "")
            {
                return Convert.ToDateTime(pDDMMYY.ToString().Trim()).ToString("MM-dd-yyyy");
            }
            return "";
        }

        public static string ConvertDMYtoMMDDYYYYHHMM(object pDDMMYY, object pHH, object pMM)
        {
            if (pDDMMYY.ToString().Trim() != "" && pHH.ToString().Trim() != "" && pMM.ToString().Trim() != "")
            {
                return Convert.ToDateTime(pDDMMYY.ToString().Trim()).ToString("MM-dd-yyyy " + pHH.ToString().Trim() + ":" + pMM.ToString().Trim());
            }
            return "";
        }

        public static string ConvertDMYtoDDMMYYYY(object pDDMMYY)
        {
            if (pDDMMYY.ToString().Trim() != "")
            {
                return Convert.ToDateTime(pDDMMYY.ToString().Trim()).ToString("dd-MMM-yyyy");
            }
            return "";
        }

        public static string ConvertDDMMYYYYtoDMY(object pDDMMMYYYY)
        {
            if (pDDMMMYYYY.ToString().Trim() != "")
            {
                return Convert.ToDateTime(pDDMMMYYYY.ToString().Trim()).ToString("dd/MM/yyyy");
            }
            return "";
        }

        //Get Thu cua Tuan
        public static int GetDayOfWeek(string strinput)
        {
            switch (strinput)
            {
                case "Sunday":
                    return 1;
                case "Monday":
                    return 2;
                case "Tuesday":
                    return 3;
                case "Wednesday":
                    return 4;
                case "Thursday":
                    return 5;
                case "Friday":
                    return 6;
                case "Saturday":
                    return 7;
            }
            return 0;
        }

        public static int SafeDataInteger(Object pValue)
        {
            if ((pValue is DBNull))
            {
                return 0;
            }
            return Convert.ToString(pValue) == "" ? 0 : Convert.ToInt32(pValue);
        }

        public static string GetCulture(HttpRequest request, System.Web.SessionState.HttpSessionState session)
        {
            var lang = string.IsNullOrEmpty(request["Lang"]) ? "vi" : request["Lang"];
            var culture = lang.Equals("vi") ? "vi-VN" : "en-US";
            return culture;
        }


        public static int RandomNumber(int min, int max)
        {
            var random = new Random();
            return random.Next(min, max);
        }

        public static string RandomString(int size, bool lowerCase)
        {
            var builder = new StringBuilder();
            var random = new Random();
            for (var i = 0; i < size; i++)
            {
                var ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            return lowerCase ? builder.ToString().ToLower() : builder.ToString();
        }

        public static string GetPassword()
        {
            var builder = new StringBuilder();
            builder.Append(RandomString(4, true));
            builder.Append(RandomNumber(1000, 9999));
            builder.Append(RandomString(2, false));
            return builder.ToString();
        }

        public static string ActiceCode(int size)
        {
            var builder = new StringBuilder();
            builder.Append(RandomString(size, true));
            builder.Append(RandomNumber(1000, 9999));
            builder.Append(RandomString(size, false));
            return builder.ToString();
        }

        public static void LoadExperience(DropDownList pCtrlName)
        {
            for (int i = 0; i <= 20; i++)
            {
                pCtrlName.Items.Add(new ListItem(i.ToString(CultureInfo.InvariantCulture), i.ToString(CultureInfo.InvariantCulture)));
            }
        }

        public static void LoadCandidateStatus(DropDownList pCtrlName)
        {
            pCtrlName.Items.Add(new ListItem("Hủy bỏ", "0"));
            pCtrlName.Items.Add(new ListItem("Nhận CV", "1"));
            pCtrlName.Items.Add(new ListItem("Thi tuyển", "2"));
            pCtrlName.Items.Add(new ListItem("Phỏng vấn", "3"));
            pCtrlName.Items.Add(new ListItem("Chờ xét", "4"));
            pCtrlName.Items.Add(new ListItem("Trúng tuyển", "5"));

        }


        public static int DateDiff(String datePart, DateTime startDate, DateTime endDate)
        {
            int result = 0;
            TimeSpan timeSpan = endDate.Subtract(startDate);
            if (datePart.ToUpper().Equals("HOUR"))
            {
                result = timeSpan.Hours;
            }
            else if (datePart.ToUpper().Equals("MINUTE"))
            {
                result = timeSpan.Minutes;
            }
            else if (datePart.ToUpper().Equals("SECOND"))
            {
                result = timeSpan.Seconds;
            }
            return result;
        }


        public static string GetParameter(HttpRequest request, int index)
        {
            var param = request["param"];
            string parameter;
            try
            {
                //   Admin/Home/1 
                var arrParam = param.Split('/');
                parameter = arrParam[index];
            }
            catch (Exception)
            {
                parameter = "";
            }
            return parameter;
        }


        public static string GetCompanyId(System.Web.SessionState.HttpSessionState session)
        {
            var companyId = "-2";
            if (session["UserName"] != null)
            {
                companyId = Convert.ToInt32(session["GroupId"]) > 1 ? session["CompanyId"].ToString() : "-1";
            }
            return companyId;
        }



        #region Encrypt - Decrypt Functions
        public static string Encrypt(string original)
        {
            return Encrypt(original, "!@#$%^&*()~_+|");
        }

        public static string Encrypt(string original, string key)
        {
            try
            {
                var objHashMD5Provider = new MD5CryptoServiceProvider();
                var keyhash = objHashMD5Provider.ComputeHash(Encoding.Unicode.GetBytes(key));

                var objDesProvider = new TripleDESCryptoServiceProvider { Key = keyhash, Mode = CipherMode.ECB };

                var buffer = Encoding.Unicode.GetBytes(original);
                return Convert.ToBase64String(objDesProvider.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
            }
            catch
            {
                return string.Empty;
            }
        }

        public static string Decrypt(string encrypted)
        {
            return Decrypt(encrypted, "!@#$%^&*()~_+|");
        }

        public static string Decrypt(string encrypted, string key)
        {
            try
            {
                var objHashMD5Provider = new MD5CryptoServiceProvider();
                byte[] keyhash = objHashMD5Provider.ComputeHash(Encoding.Unicode.GetBytes(key));
                var objDesProvider = new TripleDESCryptoServiceProvider { Key = keyhash, Mode = CipherMode.ECB };
                byte[] buffer = Convert.FromBase64String(encrypted);
                return Encoding.Unicode.GetString(objDesProvider.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length));
            }
            catch
            {
                return string.Empty;
            }
        }
        #endregion
    }
}